/*
 * @Author: fengshan0525 2735332396@qq.com
 * @Date: 2023-03-17 20:43:12
 * @LastEditors: asanupup 15465106+asanupup@user.noreply.gitee.com
 * @LastEditTime: 2025-08-06 11:22:55
 * @FilePath: \b-vue3-ts-ele-template\src\store\modules\menu.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { defineStore } from 'pinia'
import { getRouters } from '@/api/common'
import Layout from '@/layout/index.vue'
import { routes } from "@/router/baseRoutes"
export const menuStore = defineStore({
  id: 'app-menu',
  state: (): any => ({
    menuItems: false
  }),
  getters: {},
  actions: {
    async getRouters () {
      try {
        const res = await getRouters()
        const addRouters = filterAsyncRouter(res.data);

        // 从 routes 中过滤出除了 Login 和 NotFound 的路由项
        const filteredRoutes = routes.filter(route =>
          route.name !== 'Login' && route.name !== 'NotFound' && route.name !== "Preview"
        ).map(route => ({
          ...route,
          order: 0 // 设置 order 为 0
        }));
        // 合并 addRouters 和 filteredRoutes
        this.menuItems = JSON.parse(JSON.stringify([...filteredRoutes, ...addRouters]))
        return Promise.resolve(addRouters)
      } catch (e) {
        console.log(e)
      }
    }
  }
})

const filterAsyncRouter = (routers: Array<any>) => {
  return routers.filter(router => {
    if (router.children) {
      router.children = filterAsyncRouter(router.children)
    }
    if (router.component) {
      if (router.component === 'Layout') {
        router.component = Layout
      } else {
        router.component = loadView(router.component)
      }
    }
    return true
  })
}

export const loadView = (view) => {
  if (process.env.NODE_ENV === 'development') {
    return () => import(`@/views/${view}`)
  } else {
    // 使用 import 实现生产环境的路由懒加载
    return () => import(`@/views/${view}`)
  }
}
